#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cln_thread.h"
#define BUF_SIZE 1024

void *send_thread(void *arg)
{
    int clnt_sock = *((int *)arg);
    char buf[BUF_SIZE];
    char name_msg[NAME_SIZE + BUF_SIZE];
    write(clnt_sock, g_cln_name, NAME_SIZE);
    fputs("Input message(Q to quit):\n    ", stdout);
    while (1)
    {
        memset(buf, 0, BUF_SIZE);
        memset(name_msg, 0, BUF_SIZE);
        fgets(buf, BUF_SIZE, stdin);
        if (!strcmp(buf, "q\n") || !strcmp(buf, "Q\n"))
        {
            close(clnt_sock);
            exit(0);
        }
        if (buf[0] != '@')
        {
            sprintf(name_msg, "%s :%s", g_cln_name, buf);
            write(clnt_sock, name_msg, strlen(name_msg));
        }
        else
        {
            write(clnt_sock, buf, BUF_SIZE);
        }
    }
    return NULL;
}

void *recv_thread(void *arg)
{
    int clnt_sock = *((int *)arg);
    char name_msg[NAME_SIZE + BUF_SIZE];
    int read_len = 0;

    while (1)
    {
        read_len = read(clnt_sock, name_msg, sizeof(name_msg) - 1);
        if (read_len == -1)
        {
            return NULL;
        }
        name_msg[read_len] = 0;
        fputs(name_msg, stdout);
    }
    return NULL;
}